/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "EmbeddedBridgeQtSide.h"
#include <QDebug>
namespace EB {
const QString EmbeddedBridgeQtSideTAG = "EmbeddedBridgeQtSide";

std::unordered_map<QString, std::shared_ptr<IMessageHandler>> EmbeddedBridgeQtSide::msgHandlerMap;

void IMessageHandler::invokeMethod(const QString &handler, const QString &func, const QString &data)
{
    QMetaObject::invokeMethod(EB::EmbeddedBridgeQtSide::instance(), "sigSendData",
        Qt::QueuedConnection, Q_ARG(QString, handler), Q_ARG(QString, func), Q_ARG(QString, data));
}

EmbeddedBridgeQtSide *EmbeddedBridgeQtSide::instance()
{
    static EmbeddedBridgeQtSide instance;
    return &instance;
}

void EmbeddedBridgeQtSide::slotReceiveData(const QString &handler, const QString &fun, const QString &data)
{
    auto it = msgHandlerMap.find(handler);
    if (it != msgHandlerMap.end()) {
        it->second->onMessage(fun, data);
    } else {
        qCritical()<< EmbeddedBridgeQtSideTAG << "can not find handler:" << handler;
    }
}

void EmbeddedBridgeQtSide::registerMessageHandler(std::shared_ptr<IMessageHandler> handler)
{
    if (!handler) {
        return;
    }
    msgHandlerMap.insert(std::make_pair(handler->getName(), handler));
}

void EmbeddedBridgeQtSide::unregisterMessageHandler(const QString &handler)
{
    msgHandlerMap.erase(handler);
    return;
}

}